package cn.dapeng.thread;

/**
 * @BelongProject study
 * @BelongPackage cn.dapeng.thread
 * @Description 启动两个线程，一个干完，另一个再干
 * 线程间通信例子
 * @ClassName ThreadCommunicationT01
 * @Author xupenghong
 * @Date 2024/8/28 10:42
 * @Version 1.0.0
 */
public class ThreadCommunicationT01 {

    private boolean running = true;

    public synchronized void sayHi(boolean runState, String name) {
        try {
            if (runState == running) {
                System.out.println(name);
                this.notifyAll();
                running = !running;
            } else {
                this.wait();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        ThreadCommunicationT01 t = new ThreadCommunicationT01();

        Thread t1 = new Thread(() -> {
            while (true) {
                t.sayHi(true, "Hi,短");
            }
        });

        Thread t2 = new Thread(() -> {
            while (true) {
                t.sayHi(false, "hello,贼老长");
            }
        });

        t1.start();
        t2.start();
    }
}
